/*
 * decoding.cc
 * */

#include "decoding.hh"

void* Decoder::thread_hander(void * param){
	 Decoder* obj = ((param_decoder*)param)->obj;
	 free(param);
	 int i = 0;
         int filesize=0;
	 while(true){
		 BlockCp_t temp;
		 Block_t input;
		 obj->inputbuffer_->Extract(&temp);
                 int left=temp.left;
		 int blocksize=temp.blockcpSize;
		 input.blockSize=blocksize;
		 input.data=(unsigned char*)malloc(sizeof(unsigned char)*blocksize);
                   printf("the key is %s\n",temp.key);
		 obj->cryptoObj_->decryptWithKey(input.data,blocksize,temp.key,temp.data);
                 if(temp.left>0)
                    blocksize=blocksize-left-1;
                // fseek(obj->fp_,filesize,SEEK_SET);
                 filesize+=blocksize;
                 if(fwrite(input.data,blocksize,1,obj->fp_)!=1)
                        printf("error:write is failure\n");
	 }
	 return NULL;
 }


Decoder::Decoder(int n,int m,int r){
	cryptoObj_=new CryptoPrimitive(HIGH_SEC_PAIR_TYPE);
	inputbuffer_=new RingBuffer<BlockCp_t>(DECODE_RB_SIZE,true,1);
	param_decoder* param=(param_decoder*)malloc(sizeof(param_decoder));
	param->obj=this;
    fp_=NULL;
    totalBlocks_=0;
	pthread_create(&tid_,0,&thread_hander,(void*)param);
}

Decoder::~Decoder(){
  delete cryptoObj_;
  delete inputbuffer_;
}
int Decoder::setFilePointer(FILE* fp){
	fp_=fp;
	return 1;
}
int Decoder::indicateEnd(){
    pthread_join(tid_, NULL);
    return 1;
}

int Decoder::add(BlockCp_t* item){
    inputbuffer_->Insert(item, sizeof(BlockCp_t));
    printf("it has add one\n");
    return 1;
}

int Decoder::setTotal(int total){
	totalBlocks_=total;
	return 1;
}


